package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.RRException;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.vo.AccessToken;
import com.atguigu.gulimall.member.vo.SocialUser;
import com.atguigu.gulimall.member.vo.UserLoginVo;
import com.atguigu.gulimall.member.vo.UserRegistVo;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;
import org.springframework.web.client.RestTemplate;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(UserRegistVo vo) {
        MemberDao memberDao = this.getBaseMapper();
        Integer mobileCount = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", vo.getPhone()));
        if (mobileCount > 0) {
            throw new RRException(BizCodeEnume.PHONE_EXIST_EXCEPTION.getMsg(), BizCodeEnume.PHONE_EXIST_EXCEPTION.getCode());
        }
        Integer count2 = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", vo.getPhone()));
        if (count2 > 0) {
            throw new RRException(BizCodeEnume.USER_EXIST_EXCEPTION.getMsg(), BizCodeEnume.USER_EXIST_EXCEPTION.getCode());
        }
        MemberEntity memberEntity = new MemberEntity();

        MemberLevelEntity levelEntity = memberLevelDao.selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_Status", "1"));
        memberEntity.setLevelId(levelEntity.getId());
        memberEntity.setUsername(vo.getUsername());
        memberEntity.setMobile(vo.getPhone());

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encodePassword = bCryptPasswordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encodePassword);
        memberEntity.setCreateTime(new Date());
        memberDao.insert(memberEntity);
    }

    @Override
    public MemberEntity login(UserLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        MemberEntity memberEntity = this.getBaseMapper().selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (memberEntity != null) {
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            if (bCryptPasswordEncoder.matches(password, memberEntity.getPassword())) {
                return memberEntity;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public MemberEntity oauthLogin(AccessToken accessToken) {
        MemberDao memberDao = this.getBaseMapper();
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", accessToken.getUid()));
        if (memberEntity != null) {
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(accessToken.getAccess_token());
            update.setExpiresIn(accessToken.getExpires_in());
            memberDao.updateById(update);
            memberEntity.setAccessToken(accessToken.getAccess_token());
            memberEntity.setExpiresIn(accessToken.getExpires_in());
            return memberEntity;
        } else {
            memberEntity = new MemberEntity();
            try {

                String url = "https://api.weibo.com/2/users/show.json?access_token={access_token}&uid={uid}";
                Map<String, Object> requestMap = new HashMap<>();
                requestMap.put("access_token", accessToken.getAccess_token());
                requestMap.put("uid", accessToken.getUid());
                ResponseEntity<SocialUser> responseEntity = restTemplate.getForEntity(url, SocialUser.class, requestMap);
                if (responseEntity.getStatusCodeValue() == HttpStatus.OK.value()) {
                    SocialUser socialUser = responseEntity.getBody();
                    memberEntity.setNickname(socialUser.getScreen_name());
                    memberEntity.setGender("m".equals(socialUser.getGender()) ? 1 : 0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            memberEntity.setSocialUid(accessToken.getUid());
            memberEntity.setAccessToken(accessToken.getAccess_token());
            memberEntity.setExpiresIn(accessToken.getExpires_in());
            memberDao.insert(memberEntity);
            return memberEntity;
        }

    }

}